package syn;

// 不安全的买票
// 线程不安全，存在重复得到一张票或者负数等情况
public class unsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket buyTicket=new BuyTicket();
        new Thread(buyTicket,"1").start();
        new Thread(buyTicket,"2").start();
        new Thread(buyTicket,"3").start();

    }
}


class BuyTicket implements Runnable {

    private int ticketNums = 10;
    boolean flag = true; // 外部停止标志

    @Override
    public void run() {
        // 买票
        while (flag) {
            buy();
        }
    }


    // synchronized 同步方法，实现锁机制，锁的是this
    private synchronized void buy() {
        // 判断是否有票
        if (ticketNums <= 0) {
            flag = false;
            return;
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 买票
        System.out.println(Thread.currentThread().getName() + "拿到第" + ticketNums-- + "票");
    }
}